<template>
  <div id="user">
    <el-card shadow="always">
      <el-form :inline="true" size="medium" :model="userSearch" class="demo-form-inline">
        <!-- 查询表单 -->
        <el-form-item>
          <el-input v-model="userSearch.uname" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="userSearch.sex" style="width: 100px;" placeholder="性别"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="userSearch.phone" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" icon="el-icon-plus" plain @click="addUser">添加读者</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
      <!-- 读者列表表格 -->
      <el-table
          :data="userList"
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection">
        </el-table-column>
        <el-table-column
            label="读者编号"
            align="center"
            prop="uid"
            width="180"/>
        <el-table-column
            label="姓名"
            prop="uname"
            align="center"/>
        <el-table-column
            label="性别"
            prop="sex"
            align="center"/>
        <el-table-column
            label="年龄"
            prop="age"
            align="center"/>
        <el-table-column
            label="手机号"
            prop="phone"
            align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页控件 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>

    <!-- 编辑/新增读者对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="user" :rules="rules" ref="ruleForm">
        <el-form-item label="读者姓名" prop="uname" :label-width="formLabelWidth">
          <el-input v-model="user.uname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="读者性别" prop="sex" :label-width="formLabelWidth">
          <el-radio v-model="user.sex" label="男">男</el-radio>
          <el-radio v-model="user.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="读者年龄" prop="age" :label-width="formLabelWidth">
          <el-input v-model.number="user.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" :label-width="formLabelWidth">
          <el-input v-model="user.phone" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">保 存</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import userApi from "@/api/user"

export default {
  name : "UserView",
  data() {
    let checkPhone = (rule,value,callback) =>{
      if(value === '' || value == null)
        return callback(new Error('手机号不能为空'))
      let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!reg.test(value)) {
        return callback(new Error('手机号格式不正确！'))
      }else{
        callback()
      }

    }

    let checkAge = (rule, value, callback) => {
      if (value === '' || value == null) {
        return callback(new Error('年龄不能为空'))
      } else if (!Number.isInteger(value)) {
        return callback(new Error('年龄必须为数字值'))
      } else if (value < 1 || value > 100) {
        return callback(new Error('年龄必须在1-100之间'))
      } else {
        callback()
      }
    }


    return {
      userList: [],
      page: 1,        // 当前面
      pageSize: 5,    // 每页显示记录条数
      total: 100,     // 总记录数
      userSearch: {}, // 查询条件对象
      dialogFormVisible: false,  // 控制对话框显示
      user: {},       // 当前操作的读者对象
      title: '添加读者',  // 对话框标题
      formLabelWidth: '100px',  // 代表表单的标签宽度
      multipleSelection:[],     // 选中的多项读者
      uids: [],                 // 删除的读者编号列表
      // 校验规则
      rules: {
        uname: [{ required: true, message: '请输入读者姓名', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        age: [{ validator : checkAge, trigger: 'blur'}],
        phone: [{ validator : checkPhone, trigger: 'blur' }],

      }
    }
  }
  ,
  created() {
    this.search()
  },
  methods: {

    // 条件查询带分页，""可查出全部数据
    async search() {
      const {data: res} = await userApi.search(this.page, this.pageSize, this.userSearch)
      if (res.code === 200) {
        this.userList = res.data.pr.rows
        this.total = res.data.pr.total
      }
    },
    //添加读者
    addUser() {
      //跟修改框共用得改标题。
      this.title = "添加读者"


      this.user = {}
      this.dialogFormVisible = true
    },
    // 保存读者
    saveUser() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const url = this.user.uid ? '/user/update' : '/user/add';
          const method = this.user.uid ? 'put' : 'post';
          const {data:res} = await userApi.save(url,method,this.user)
          console.log("res:",res)
          if (res.code === 200) {
            this.$message({ type: 'success', message: res.message });
            this.dialogFormVisible = false;
            this.search();
          } else {
            this.$message({ type: 'error', message: res.message });
          }

        } else {
          console.log("验证失败！")
          return false
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },
    // 当pagesize大小发生改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.search()
      console.log(`每页 ${val} 条`);
    },
    // 当页码page发生改变时触发
    handleCurrentChange(val) {
      this.page = val
      this.search()
      console.log(`当前页: ${val}`);
    },
    // 修改读者
    handleEdit(index, row) {

      this.title = '修改读者'

      //修改需要信息回显
      this.user = row
      this.dialogFormVisible = true
    },
    handleDelete(index, row) {
      this.uids = row ? [row.uid] : this.multipleSelection.map(m => m.uid);
      this.$confirm(`确认删除编号为${this.uids}的读者吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let _this = this
        userApi.delete(this.uids)
            .then(({data:res}) => {
              console.log("res:",res)
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: res.message,
                  onClose: () => {
                    _this.search()
                  }
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  }
}
</script>

<style>
.el-card {
  width: 100%;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
